package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collection;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    //获取当前登录（认证）用户的用户名
    @RequestMapping("/getUsername")
    public Result getLoginUsername(){
        try{
            User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            String username = user.getUsername();
            String password = user.getPassword();
            Collection<GrantedAuthority> authorities = user.getAuthorities();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,username);
        }catch (Exception e){
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }


    @Reference
    private UserService userService;

    @RequestMapping("/getRoleAndMenu")
    public Result getRoleAndMenu(){
        //从session中获取用户对象
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        //如果User不为空
        if (user != null){

            //获取用户UserName
            String username = user.getUsername();
            //根据UserName获得用户角色ID
            Integer roleId = userService.findRoleByUserName(username);

            try {

                //根据用户角色ID查询菜单数据
                List<Menu> list = userService.getMenuByRoleId(roleId);
                return new Result(true,MessageConstant.GET_MENU_SUCCESS,list);

            }catch (Exception e){
                e.printStackTrace();
                return new Result(false,MessageConstant.GET_MENU_FAIL);
            }
        }
        return new Result(false,MessageConstant.GET_MENU_FAIL);
    }

}
